package com.cabal.module.security.service.impl;

import com.gvt.apollo.ApolloSdk;
import com.gvt.apollo.utils.SecurityUtils;
import com.cabal.module.security.entity.KeyPairEntity;
import com.cabal.module.security.service.SecurityService;
import org.springframework.stereotype.Service;

import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SignatureException;
import java.security.spec.InvalidKeySpecException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Predicate;

/**
 * @author jiaozi<liaomin @ gvt861.com>
 * @since JDK8
 * Creation time：2019/8/13 18:11
 */
@Service
public class SecurityServiceImpl implements SecurityService {
    public static Map<String, KeyPairEntity> keysMap = new HashMap<>();

    public static void main(String[] args) {
        String key = "MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBAK/+gYSN6E9DID76KRyMAwqClWjdOkF+/k5EQqMwdHjaTXPz469EcmFAnDB5nICdmbfH7dfYBiKoxYeT5UNvAPMSQewR1DMNg3mdm1ZBGwJ0gUP8zD0VgqD7SOWdsf+LRYFSVZQjPT17OllT/Ikvy5tblZxJPEBzyPYCtvzUL+A5AgMBAAECgYBXOOs3ppzbq4jvrUtyunFHZDBoKDwW+blPUMU1223d91MrhFPzKRkG2d6Op7bIh1MHoi5eKtHfm4VKDCIzqW/uNVkVBmn1VIor/YkjpNZphewyux2yc3tazoE26jLQnZZSCXQ6THH3tEZGHApBAGTj/FYQLEQe/6D1sVf2QM3fgQJBANSCrNfPQwes2512R4xG+cBkncz251a9yZiGGbUHH/LaJaPMH7jJvmf1jq98chDBjbW+ncKkguYu62aSmHZtEXsCQQDUAsJiITgrK5wsnt5sPJc8I0PDwU2J8mFFSG2991YCCyPxk8Qca2SLFm2ObbOp9tmudkvwHJHj3DTWjH9pFATbAkEAl1KR13674VxCagbOfeIQd+Jtx4TNSKQOSHC9H336Twjtoox4zjHCRu7Bcs5vvuTEjvU0C2Tv3Q7uCvU6YaHavwJANHl+XUV1npHLtOuZh9azZAoicqg8peEdHEXiC7vVSOoy+k8lohceqqJheXhDmNTlah4Ti5m2rlxJo7TgsERpMwJBAKuohvK99gBCu2ojHNKvG1bypiyrpS6b3p/AMCn4IoE9hhbzDhbpd2OFrFcZnLOEON0MKB3X/DW/3p+7rt4c1ds=";
        System.out.println(key.length());
    }

    /**
     * 本地key
     */

    private String[] supportVersion=new String[]{"1.0.0"};

    @Override
    public boolean checkAppId(String appid) {
        if(keysMap.containsKey(appid)){
            return true;
        }
        return false;
    }

    @Override
    public boolean checkVersion(String version) {
        return Arrays.stream(supportVersion).filter(new Predicate<String>() {
            @Override
            public boolean test(String s) {
                return s.equals(version);
            }
        }).findFirst().isPresent();
    }

    @Override
    public String getPublicKey(String appid) {
        return keysMap.get(appid).getPublicKey();
    }

    @Override
    public String getprivateKey(String appid) {
        return keysMap.get(appid).getPrivateKey();
    }


    private ApolloSdk apolloSdk=new ApolloSdk();

    @Override
    public boolean checkSign(String publicKey,String data) throws InvalidKeySpecException, NoSuchAlgorithmException, SignatureException, InvalidKeyException {
        return apolloSdk.validateSign(SecurityUtils.getPubKey(publicKey),data);
    }
}
